<template>
  <div>
    <div class="pageTopTitle">合作项目</div>
    <div class="app-container">
      <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="80px" size="small">
        <el-form-item label="项目客户" prop="clientId">
          <el-input
            v-model="queryParams.clientId"
            clearable
            placeholder="请输入项目客户"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="渠道" prop="channelId">
          <el-input
            v-model="queryParams.channelId"
            clearable
            placeholder="请输入渠道"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="app-container mt20">
      <el-row :gutter="10" class="mb20">
        <el-col :span="1.5">
          <el-button
            icon="el-icon-plus"
            plain
            size="mini"
            type="primary"
            @click="handleAdd"
          >新增
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="projectList">
        <el-table-column label="项目信息">
          <template slot-scope="scope">
            <div> {{ scope.row.name }}</div>
            <div style="margin: 5px 0">
              <el-tag>{{ scope.row.type }}</el-tag>
            </div>
            <div>{{ scope.row.mainUser }}</div>
            <div>{{ scope.row.phone }}</div>
          </template>
        </el-table-column>
        <el-table-column label="项目状态" width="180px">
          <template slot-scope="scope">
            <div>
              <el-dropdown @command="handleStatusChange(scope.row, $event)">
                <span class="el-dropdown-link">
                  <span v-if="scope.row.status === 1" style="color: #FF7D00">推进中</span>
                  <span v-else style="color: #00B42A">已完成</span><i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="1">推进中</el-dropdown-item>
                  <el-dropdown-item command="2">已完成</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
            <div class="fs-12">项目立项：{{ scope.row.startAt }}</div>
            <div v-if="scope.row.endAt" class="fs-12">项目完成：{{ scope.row.endAt }}</div>
          </template>
        </el-table-column>
        <el-table-column label="项目总金额" prop="money">
          <template slot-scope="scope">
            <div>
              <span>总金额：{{ scope.row.money }}</span>
            </div>
            <div style="color: #00B42A">
              <span>已收款：{{ scope.row.paidMoney }}</span>
            </div>
            <div style="color: #999">
              <span>未收款：{{ scope.row.money - scope.row.paidMoney }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="项目专家" >
          <template slot-scope="scope">
            <div v-if="scope.row.expertList && scope.row.expertList.length === 0">
              <el-link  type="success" style="font-size: 18px;" :underline="true">0</el-link>
            </div>
            <div v-else style="display: flex; flex-wrap: wrap;">
              <el-tag size="mini"  v-for="expert in scope.row.expertList" style="margin-right: 5px; margin-bottom: 5px" :key="expert.id" type="warning">{{ expert.name }}</el-tag>
            </div>
            <el-button
              size="mini"
              type="text"
              @click="openExpert(scope.row)"
            >添加
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="项目客户">
          <template slot-scope="scope">
            <div v-if="scope.row.clientList && scope.row.clientList.length === 0">
              <el-link  type="success" style="font-size: 18px;" :underline="true">0</el-link>
            </div>
            <div v-else style="display: flex; flex-wrap: wrap;">
              <el-tag v-for="expert in scope.row.clientList" style="margin-right: 5px; margin-bottom: 5px" size="mini" :key="expert.id" type="warning">{{ expert.name }}</el-tag>
            </div>
            <el-button
              size="mini"
              type="text"
              @click="openClient(scope.row)"
            >添加
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="归属渠道">
          <template slot-scope="scope">
            <div v-if="scope.row.channelList && scope.row.channelList.length === 0">
              <el-link  type="success" style="font-size: 18px;" :underline="true">0</el-link>
            </div>
            <div v-else style="display: flex; flex-wrap: wrap;">
              <el-tag v-for="channel in scope.row.channelList" style="margin-right: 5px; margin-bottom: 5px" size="mini" :key="channel.id" type="warning">{{ channel.name }}</el-tag>
            </div>
            <el-button
              size="mini"
              type="text"
              @click="openChannel(scope.row)"
            >添加
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="项目备注" prop="remark"/>
        <el-table-column class-name="small-padding fixed-width" label="操作" width="120px">
          <template slot-scope="scope">
            <div>
              <el-button
                size="mini"
                style="color: #00B42A !important"
                type="text"
                @click="handleMoney(scope.row)"
              >项目收款
              </el-button>
            </div>
            <el-button
              size="mini"
              type="text"
              @click="handleUpdate(scope.row)"
            >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :limit.sync="queryParams.pageSize"
        :page.sync="queryParams.pageNum"
        :total="total"
        @pagination="getList"
      />

      <!-- 添加或修改合作项目对话框 -->
      <el-drawer
        :title="title"
        :visible.sync="open"
        :wrapper-closable="false"
        size="35%"
      >
        <div class="drawer-content">
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="项目类型" prop="name">
              <el-radio-group v-model="form.type" style="width: 100%;">
                <el-radio-button border label="内训项目">内训</el-radio-button>
                <el-radio-button border label="咨询项目">咨询</el-radio-button>
                <el-radio-button border label="公开课">公开课</el-radio-button>
                <el-radio-button border label="陪跑项目">陪跑</el-radio-button>
                <el-radio-button border label="其他项目">其他</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="项目名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入项目名称"/>
            </el-form-item>
            <el-form-item label="项目负责人" prop="mainUser">
              <el-input v-model="form.mainUser" placeholder="请输入项目负责人"/>
            </el-form-item>
            <el-form-item label="联系方式" prop="phone">
              <el-input v-model="form.phone" maxlength="11" placeholder="请输入联系方式"/>
            </el-form-item>
            <el-form-item label="立项时间" prop="startAt">
              <el-date-picker v-model="form.startAt"
                              clearable
                              placeholder="请选择立项时间"
                              style="width: 100%;"
                              type="date"
                              value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="计划完成时间" prop="endAt">
              <el-date-picker v-model="form.endAt"
                              clearable
                              placeholder="请选择项目计划完成时间"
                              style="width: 100%;"
                              type="date"
                              value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="项目总金额" prop="money" required>
              <el-input v-model="form.money" placeholder="请输入项目总金额">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="项目详情" prop="detail">
              <Editor v-model="form.detail" :min-height="300"></Editor>
            </el-form-item>
            <el-form-item label="项目备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入项目备注" rows="3" type="textarea"/>
            </el-form-item>
          </el-form>
        </div>
        <div class="drawer-footer">
          <el-button size="small" style="width: 120px;" type="primary" @click="submitForm">确 定</el-button>
          <el-button size="small" style="width: 120px;" @click="cancel">取 消</el-button>
        </div>
      </el-drawer>

      <el-drawer
        :visible.sync="drawer"
        :with-header="false"
        size="35%"
      >

        <div class="drawer-content">
          <el-form ref="recordForm" :model="recordForm" :rules="recordRules" label-position="top">
            <el-form-item label="收款账户" prop="accountId">
              <el-select v-model="recordForm.accountId" :remote-method="remoteMethod" filterable
                         placeholder="选择收款账户" remote style="width: 100%;"
              >
                <el-option v-for="item in accountList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-col :span="11">
                <el-form-item label="收款金额" prop="money">
                  <el-input v-model="recordForm.money" placeholder="请输入收款金额"/>
                </el-form-item>
              </el-col>
              <el-col :span="2" class="line">
                <el-form-item label=" ">
                  <span style="text-align: center">-</span>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="到账时间" prop="date">
                  <el-date-picker v-model="recordForm.date"
                                  clearable
                                  placeholder="请选择收款时间"
                                  style="width: 100%;"
                                  type="date"
                                  value-format="yyyy-MM-dd"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-form-item>
            <el-form-item label="收款备注" prop="remark">
              <el-input v-model="recordForm.remark" placeholder="请输入收款备注" rows="2" type="textarea"/>
            </el-form-item>
          </el-form>
          <el-button size="small" style="width: 120px;" type="primary" @click="submitRecordForm">保存收款</el-button>
          <div class="mt24">
            <el-table :data="projectRecordList">
              <el-table-column label="收款账户" prop="accountId">
                <template slot-scope="scope">
                  <span>{{ scope.row.account.name }}</span>
                </template>
              </el-table-column>
              <el-table-column label="收款金额-时间" prop="money">
                <template slot-scope="scope">
                  <div style="color: #F53F3F">收款：{{ scope.row.money }}</div>
                  <div>{{ scope.row.date }}</div>
                </template>
              </el-table-column>
              <el-table-column label="备注" prop="remark"/>
              <el-table-column class-name="small-padding fixed-width" label="操作" width="80px">
                <template slot-scope="scope">
                  <el-button
                    disabled
                    size="mini"
                    type="text"
                  >删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-drawer>


      <el-dialog title="选择专家" :visible.sync="expertDialogVisible" center width="800px">
        <div class="text-center mb20">
          <el-transfer
            style="text-align: left; display: inline-block"
            v-model="editExpertForm.expertIdList"
            filterable
            :titles="['专家', '已选择']"
            :button-texts="['到左边', '到右边']"
            :data="expertList">
          </el-transfer>
        </div>
        <div style="text-align: center">
          <el-button type="primary" @click="subExpertCheck">确认选择</el-button>
        </div>
      </el-dialog>

      <el-dialog title="选择客户" :visible.sync="clientDialogVisible" center width="800px">
        <div class="text-center mb20">
          <el-transfer
            style="text-align: left; display: inline-block"
            v-model="editClientForm.clientIdList"
            filterable
            :titles="['客户', '已选择']"
            :button-texts="['到左边', '到右边']"
            :data="clientList">
          </el-transfer>
        </div>
        <div style="text-align: center">
          <el-button type="primary" @click="subClientCheck">确认选择</el-button>
        </div>
      </el-dialog>

      <el-dialog title="选择渠道" :visible.sync="channelDialogVisible" center width="800px">
        <div class="text-center mb20">
          <el-transfer
            style="text-align: left; display: inline-block"
            v-model="editChannelForm.channelIdList"
            filterable
            :titles="['渠道', '已选择']"
            :button-texts="['到左边', '到右边']"
            :data="channelList">
          </el-transfer>
        </div>
        <div style="text-align: center">
          <el-button type="primary" @click="subChannelCheck">确认选择</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { listAccount } from '@/api/web/account'
import { listCollection, addCollection, updateCollection } from '@/api/web/projectRecored'

import {
  listProject,
  getProject,
  delProject,
  addProject,
  updateProject,
  editClient,
  editExpert,
  editChannel
} from '@/api/web/project'
import { listClient } from '@/api/web/client'
import { listExpert } from '@/api/web/expert'
import { listChannel } from '@/api/web/channel'

export default {
  name: 'Project',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合作项目表格数据
      projectList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      drawer: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        status: null,
        type: null
      },

      expertList:[],
      clientList: [],
      channelList:[],

      expertDialogVisible: false,
      clientDialogVisible: false,
      channelDialogVisible: false,

      editExpertForm:{
        projectId: null,
        expertIdList: []
      },
      editClientForm:{
        projectId: null,
        clientIdList: []
      },

      editChannelForm:{
        projectId: null,
        channelIdList: []
      },

      // 收款账户列表
      accountList: [],
      // 收款记录列表
      projectRecordList: [],
      // 表单参数
      form: {},
      // 收款记录表单
      recordForm: {},
      recordRules: {
        accountId: [
          { required: true, message: '收款账户不能为空', trigger: 'blur' }
        ],
        money: [
          { required: true, message: '收款金额不能为空', trigger: 'blur' }
        ],
        date: [
          { required: true, message: '收款时间不能为空', trigger: 'blur' }
        ]
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '项目名称不能为空', trigger: 'blur' }
        ],
        money: [
          { require: true, message: '项目总金额不能为空', trigger: 'blur' }
        ],
        mainUser: [
          { required: true, message: '项目负责人不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '联系方式不能为空', trigger: 'blur' }
        ],
        startAt: [
          { required: true, message: '立项时间不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '项目类型不能为空', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getExpert()
    this.getClient()
    this.getList()
    this.getChannel()
  },
  methods: {
    /** 查询合作项目列表 */
    getList() {
      this.loading = true
      listProject(this.queryParams).then(response => {
        this.projectList = response.rows
        this.total = response.total
        this.loading = false
      })

      listAccount().then(resp => {
        this.accountList = resp.rows
      })
    },
    getAccountRecordList(projectId) {
      listCollection({
        projectId: projectId
      }).then(response => {
        this.projectRecordList = response.rows
      })
    },

    handleStatusChange(row, command) {
      updateProject({
        id: row.id,
        status: command
      }).then(response => {
        this.$modal.msgSuccess('状态修改成功')
        this.getList()
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        mainUser: null,
        phone: null,
        startAt: null,
        endAt: null,
        type: null,
        money: null,
        detail: null,
        remark: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },

    /** 选择专家提交确认 */
    subExpertCheck(){
      if(this.editExpertForm.expertIdList.length === 0){
        this.$message.error('请选择专家')
        return
      }
      editExpert(this.editExpertForm).then(response => {
        this.expertDialogVisible = false
        this.getList()
      })
    },

    /** 选择专家提交确认 */
    subClientCheck(){
      if(this.editClientForm.clientIdList.length === 0){
        this.$message.error('请选择客户')
        return
      }
      editClient(this.editClientForm).then(response => {
        this.clientDialogVisible = false
        this.getList()
      })
    },

    /** 选择渠道提交确认 */
    subChannelCheck(){
      if(this.editChannelForm.channelIdList.length === 0){
        this.$message.error('请选择渠道')
        return
      }
      editChannel(this.editChannelForm).then(response => {
        this.channelDialogVisible = false
        this.getList()
      })
    },

    getClient() {
      listClient({ pageSize: 100 }).then(response => {
        this.clientList = response.rows.map(item => {
          return {
            key: item.id,
            label: item.name
          }
        })
      })
    },
    getExpert() {
      listExpert({ pageSize: 100 }).then(response => {
        this.expertList = response.rows.map(item => {
          return {
            key: item.id,
            label: item.name
          }
        })
      })
    },
    getChannel(){
      listChannel({ pageSize: 100 }).then(response => {
        this.channelList = response.rows.map(item => {
          return {
            key: item.id,
            label: item.name
          }
        })
      })
    },

    openExpert(row) {
      this.editExpertForm.projectId = row.id
      this.expertDialogVisible = true
      this.editExpertForm.expertIdList = row.expertList.map(item => item.id)
    },

    openClient(row) {
      this.editClientForm.projectId = row.id
      this.clientDialogVisible = true
      this.editClientForm.clientIdList = row.clientList.map(item => item.id)
    },

    openChannel(row) {
      this.editChannelForm.projectId = row.id
      this.channelDialogVisible = true
      this.editChannelForm.channelIdList = row.channelList.map(item => item.id)
    },


    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加合作项目'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getProject(id).then(response => {
        this.form = response.data
        if (this.form.client) {
          this.form.clientName = this.form.client.name
        }
        this.open = true
        this.title = '修改合作项目'
      })
    },
    /**
     * 项目收款
     * @param row
     */
    handleMoney(row) {
      this.recordForm.projectId = row.id
      this.getAccountRecordList(row.id)
      this.drawer = true
    },

    submitRecordForm() {
      this.$refs['recordForm'].validate((valid) => {
        if (valid) {
          if (this.recordForm.id != null) {
            updateCollection(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
            })

          } else {
            addCollection(this.recordForm).then(response => {
              this.$modal.msgSuccess('新增成功')
            })
          }
          setTimeout(() => {
            this.getAccountRecordList(this.recordForm.projectId)
            this.recordForm.money = ''
            this.recordForm.date = ''
            this.recordForm.remark = ''
          }, 800)
        }
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          // 金额是否为数字
          if (isNaN(this.form.money)) {
            this.$message.error('项目总金额填写错误')
            return
          }
          if (this.form.id != null) {
            updateProject(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addProject(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除合作项目编号为"' + ids + '"的数据项？').then(function() {
        return delProject(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      })
    }
  }
}
</script>


<style lang="scss" scoped>
.drawer-content {
  padding: 0 30px 80px 20px;
}

.drawer-footer {
  position: absolute;
  bottom: 0;
  box-sizing: border-box;
  text-align: right;
  padding: 16px;
  width: 100%;
  border-top: 1px solid #eee;
  background-color: #fff;
}

::v-deep .el-form-item__label {
  font-weight: 500 !important;
}

::v-deep .el-form--label-top .el-form-item__label {
  padding: 0 0 4px 0 !important;
}


::v-deep .no-spin-arrows input::-webkit-outer-spin-button,
::v-deep .no-spin-arrows input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

::v-deep .no-spin-arrows input[type="number"] {
  -moz-appearance: textfield;
}
</style>
